package storage;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import network.messages.KrakenClientMsg;
import network.messages.KrakenServerMsg;
import network.ssl.KrakenSSLClient;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import tools.AppletConstant;
import tools.ConfParser;

import bdd.sql.server.bean.ServerCentral;
import bdd.sql.server.bean.ServerStorage;
import bdd.sql.server.bean.Video;
import bdd.sql.server.hibernate.HibernateUtil;

public class VideoTransfert {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//récupérer ip du serveur de stockage courant
		String ipSiteStockage = "";
		String ipServCentral = "";
		String destinationVideoPath = "";
		
		ConfParser parser = new ConfParser();
		try {
			parser.parse(new File(AppletConstant.STOR_CONF));
		} catch (IOException e) {
			e.printStackTrace();
		}

		ipSiteStockage = parser.getValue("IP_SERVER");
		ipServCentral = parser.getValue("IP_CENTRAL");
		destinationVideoPath = parser.getValue("CENTRAL_VIDEOS_PATH");
		
		Session session = HibernateUtil.getSession();
		ServerStorage siteStorage = (ServerStorage)session.createCriteria(ServerStorage.class).
				add(Restrictions.like("storserv_ip", ipSiteStockage)).list().get(0);
		
		destinationVideoPath += siteStorage.getStorserv_name() + "-" + ipSiteStockage +System.getProperty("file.separator");
		
		ServerStorage centralStorage = (ServerStorage) ((ServerCentral) session.createCriteria(ServerCentral.class).
				add(Restrictions.like("servcentr_ip", ipServCentral)).list().get(0)).getServerStorage();
		
		String ipCentralStockage = centralStorage.getStorserv_ip();
		
		List<Video> videosToTransfert = session.createCriteria(Video.class).
				add(Restrictions.like("storage", siteStorage)).list();
		
		ArrayList<String> msg_list = new ArrayList<String>();
		msg_list.add(KrakenClientMsg.KRAKEN_SSL_CLIENT.makeCommand());
		msg_list.add(KrakenClientMsg.CREATE_DIRECTORY.makeCommand(" "+destinationVideoPath));
		
		String osSeparator = System.getProperty("file.separator");
		HashMap<String,String> chemins = new HashMap<String,String>();
		String finalPath = "";
		String savedPath = "";
		
		for(Video video : videosToTransfert){
			String vidName = video.getVideo_name();
			
			String[] path_informations = vidName.split("_");
			finalPath = destinationVideoPath
					+ path_informations[0] + osSeparator //camName-camIP
					+ path_informations[1].substring(0,4) + osSeparator //année
					+ path_informations[1].substring(4,6) + osSeparator //mois
					+ path_informations[1].substring(6,8) + osSeparator; //jour
			
			if(!finalPath.equals(savedPath)){
				savedPath = finalPath;
				msg_list.add(KrakenClientMsg.CREATE_DIRECTORY.makeCommand(" "+finalPath));
			}
			chemins.put(vidName, finalPath+vidName);
			msg_list.add(KrakenClientMsg.COPY_FILE.makeCommand(" "+video.getVideo_path(), " "+finalPath+video.getVideo_name(), " "+video.getVideo_weight()));
		}
		msg_list.add(KrakenClientMsg.END_SSL_CLIENT.makeCommand());

		KrakenSSLClient client = new KrakenSSLClient(msg_list, ipCentralStockage, 0);
		client.connect();
		client.communicate();
		
		if(client.getFinalAnswer().equalsIgnoreCase(KrakenServerMsg.END_SSL_SERVER.toString())){
			System.out.println("Transfert réussi !");
			Transaction tx = session.beginTransaction();
			for(Video video : videosToTransfert){
				new File(video.getVideo_path()).delete();
				video.setStorage(centralStorage);
				video.setVideo_path(chemins.get(video.getVideo_name()));
				session.save(video);
			}
			tx.commit();
			session.close();
			System.out.println("Sauvegardes en bases de données réussies!");
		}
	}

}
